//
//  RESeverTableViewCell.m
//  录音
//
//  Created by ywy on 2016/12/25.
//  Copyright © 2016年 Wely. All rights reserved.
//

#import "RESeverTableViewCell.h"
#import "RECheckLogin.h"
#import <SVProgressHUD/SVProgressHUD.h>

@implementation RESeverTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
   
    self.backView.layer.borderColor = RERGBColor(225, 225, 225).CGColor;
    self.backView.layer.masksToBounds = NO;
    //设置阴影的颜色
    self.backView.layer.shadowColor=RERGBColor(225, 225, 225).CGColor;
    //设置阴影的偏移量，如果为正数，则代表为往右边偏移
    self.backView.layer.shadowOffset=CGSizeMake(1, 1);
    //设置阴影的透明度(0~1之间，0表示完全透明)
    self.backView.layer.shadowOpacity=0.5;
    
    [self.progress setTrackTintColor:RERGBColor(249, 182, 70)];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, REScreenW-20, self.layerView.frame.size.height) byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = CGRectMake(0, 0, REScreenW-20, self.layerView.frame.size.height);
    maskLayer.path = maskPath.CGPath;
    self.layerView.layer.mask = maskLayer;
    self.progress.layer.masksToBounds = YES;
    self.progress.layer.cornerRadius = 5;
    self.ispaly = YES;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}


-(void)showData:(RETrackList*)model
{
    _baseModel = model;
    self.titleLabel.text = model.albumName;
    self.progress.progress = 0;
    self.progressTime.text  =@"00:00";
    self.totalTimeLabel.text = [NSString stringWithFormat:@" / %@",model.albumLength];
}
// 分享
- (IBAction)shareClick:(UIButton *)sender {
    if (self.listBloack) {
        self.listBloack(1001,_baseModel,NO,self.progress,self,_indexPath);
    }
    
}
// 删除
- (IBAction)deleteClick:(UIButton *)sender {
    if (self.listBloack) {
        self.listBloack(1002,_baseModel,NO,self.progress,self,_indexPath);
    }
    

    
}
// 播放
- (IBAction)playClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    
//    [self stopOrPlayWithModel:_baseModel flag:sender.selected];
//    if (sender.selected == true) {
//        if (_delegate && [_delegate respondsToSelector:@selector(stopPlayWithIndex:withFlag:)]) {
//            [self.delegate stopPlayWithIndex:_indexPath withFlag:sender.selected];
//        }
//    }

    if (self.listBloack) {
        self.listBloack(1003,_baseModel,sender.selected,self.progress,self,_indexPath);
    }
    
}

- (void)stopOrPlayWithModel:(RETrackList *)baseModel flag:(BOOL)flag{
    
    if (flag == YES) {
        
        if (self.ispaly) {
            [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
            [self.selfPlayer.currentItem removeObserver:self  forKeyPath:@"status"];
            
            AVAudioSession *session = [AVAudioSession sharedInstance];
            [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
//          [session setCategory:AVAudioSessionCategoryPlayback error:nil];
            [session setActive:NO error:nil];
//            NSURL *localURL = [NSURL fileURLWithPath:[RECheckLogin getlocalPath:@"/" allStr:baseModel.albumVoice]];
//            AVURLAsset *localAssert = [[AVURLAsset alloc]initWithURL:localURL options:nil];
            NSURL  * baseUrl = [NSURL URLWithString:[baseModel.albumVoice stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
            AVURLAsset *localAssert = [[AVURLAsset alloc]initWithURL:baseUrl options:nil];
            //AVPlayerItem 他是对assert对应资源的一种整体描述，包括能够播放，以及影片长度等内容
            AVPlayerItem *item = [[AVPlayerItem alloc]initWithAsset:localAssert];
            //使用item生成player，这里会对影片进行预加载分析，然后更新item的状态
            self.selfPlayer = [AVPlayer playerWithPlayerItem:item];
            self.selfPlayer.volume = 1;
            //监听AVPlayerItem的status状态，当status状态为readyToPlayer时，我们认为影片时可以播放的
            [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.selfPlayer.currentItem];
        }else
        {
            [self.selfPlayer play];
        }
    }else
    {
        // stop
        [self stopPlay];
    }
    
}

- (void)playbackFinished:(NSNotification *)notifi{
    self.progress.progress = 0.0;
    [self.palyButton setSelected:NO];
    self.ispaly = YES;
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    __weak typeof(self) weakSelf = self;
    if ([keyPath isEqualToString:@"status"]) {
        
        AVPlayerItem *item = (AVPlayerItem*)object;
        
        if (item.status == AVPlayerItemStatusReadyToPlay) {
            //这里影片可以播放
            [self.selfPlayer play];
            [self.selfPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
                //time是指当前影片播放的时间
                //得到影片的总时间
                CMTime totalTime = weakSelf.selfPlayer.currentItem.duration;
                //CMTimeGetSeconds 把CMTime转换为秒数
                CGFloat currentTimeSeconds = CMTimeGetSeconds(time);
                CGFloat totalSeconds = CMTimeGetSeconds(totalTime);
                
                int  minnute = currentTimeSeconds/60;
                int second = currentTimeSeconds-minnute*60;
                weakSelf.progressTime.text = [NSString stringWithFormat:@"%02d:%02d",minnute,second];
                //更新进度
                [weakSelf.progress setProgress:currentTimeSeconds*1.0/totalSeconds animated:YES];
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:@"录音文件暂时无法播放"];
        }
    }
}

- (void)stopPlay{
    [self.selfPlayer pause];
    self.ispaly = NO;
}


@end
